import { OnInit, Component, Input, ViewChild } from '@angular/core';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { SystemFileDTO } from 'src/app/project/model/icm/icm-global/system-file/system-file-dto';
import { ObjectUtil } from 'src/app/project/utils/object-util';
import { TABLE_PARAMETER } from '../../setting/table-parameter';
import { STColumn } from '@delon/abc';
import { SystemFileService } from 'src/app/project/service/icm/icm-global/system-file/system-file.service';
import { NzMessageService } from 'ng-zorro-antd';
import { AttachSmallComponent } from '@shared/common-component/attach-small.component';

@Component({
  selector: 'app-system-file-list',
  templateUrl: './system-file-list.component.html',
})
export class SystemFileListComponent implements OnInit {
  constructor(private systemFileService: SystemFileService, private msg: NzMessageService) {}

  @ViewChild('attachSmallComponent', { static: false })
  attachSmallComponent: AttachSmallComponent;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 查询参数
   */
  @Input()
  queryParams;

  /**
   * 请求数据标识
   */
  loading = false;

  /**
   * 表格数据
   */
  tableData: Array<SystemFileDTO> = [];

  /**
   * 列表参数
   */
  TABLE_PARAMETER = ObjectUtil.deepClone(TABLE_PARAMETER);

  /**
   * 表格的列定义
   */
  stColumns: STColumn[] = [
    {
      title: '序号',
      render: 'number',
      width: '2%',
      className: 'text-center',
    },
    {
      title: '文件原名称',
      index: 'originalName',
      width: '6%',
      className: 'text-left text-truncate',
    },
    {
      title: '文件存储名称',
      index: 'name',
      width: '8%',
      className: 'text-left text-truncate',
    },
    {
      title: '文件类型',
      index: 'type',
      width: '4%',
      className: 'text-left',
    },
    {
      title: '操作',
      render: 'operations',
      index: 'operation',
      width: '4%',
      className: 'text-center',
      fixed: 'right',
    },
  ];

  /**
   * 表格变化事件，用于双击、排序，翻页等操作
   * @param e event
   */
  change(e: any): void {
    // 双击事件
    if (e.type === 'dblClick') {
      this.loading = true;
      // tslint:disable-next-line: deprecation
      this.systemFileService.downloadFileContentById(e.dblClick.item.code).subscribe(
        data => {
          //   this.dictionaryDetailComponent.edit(true, data);
        },
        null,
        () => {
          this.loading = false;
        },
      );
    }
    // 排序事件
    if (e.type === 'sort') {
      if (e.sort.map) {
        const temp = e.sort.map.sort;
        if (temp) {
          this.queryOptions.sort = temp.replace(/[\.-]/g, ',');
        }
      }
      this.loadData();
    }
    // 翻页设置
    if (e.type === 'ps' || e.type === 'pi') {
      this.queryOptions.page = e.pi - 1;
      this.queryOptions.size = e.ps;
      this.loadData();
    }
  }

  /**
   * 获取数据
   */
  loadData() {
    this.loading = true;
    // tslint:disable-next-line: deprecation
    this.systemFileService.getFiles(this.queryOptions, this.queryParams.originalName, this.queryParams.type).subscribe(
      data => {
        if (data) {
          this.tableData = data.data;
          this.TABLE_PARAMETER.page.total = data.totalRecords;
        }
      },
      null,
      () => {
        this.loading = false;
      },
    );
  }

  /**
   * 上传附件
   */
  uploadAttach(fileType: string, files?: SystemFileDTO[]) {
    // this.fileType = fileType;
    // this.attachFiles = files;
    this.attachSmallComponent.isVisible = true;
    // this.isReview = this.readOnly;
    // this.isShow = !this.readOnly;
  }

  /**
   * 将附件弹射回detail
   */
  resultChange(files: SystemFileDTO[]) {
    // this.attachFiles = files;
    // this.budgetAdjustment.files = this.attachFiles;
    // this.budgetAdjustment.fileIds = [];
    // this.budgetAdjustment.files.forEach(file => {
    //   this.budgetAdjustment.fileIds.push(file.id);
    // });
  }

  /**
   * 下载文件
   */
  downloadFile(row: SystemFileDTO) {
    this.loading = true;
    // tslint:disable-next-line: deprecation
    this.systemFileService.downloadFileContentById(row.id).subscribe(
      blob => {
        const uA = window.navigator.userAgent; // 判断浏览器内核
        const isIE =
          /msie\s|trident\/|edge\//i.test(uA) &&
          !!(
            'uniqueID' in document ||
            'documentMode' in document ||
            'ActiveXObject' in window ||
            'MSInputMethodContext' in window
          );
        const binaryData = [];
        binaryData.push(blob.body);
        const objectUrl = window.URL.createObjectURL(new Blob(binaryData, { type: blob.body.type }));
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = objectUrl;
        a.download = row.originalName ? row.originalName : '';
        if (isIE) {
          // 兼容IE11无法触发下载的问题
          navigator.msSaveBlob(new Blob(binaryData), a.download);
        } else {
          a.click();
        }
        a.remove();
      },
      null,
      () => {
        this.loading = false;
      },
    );
  }

  /**
   * 字典如无字典值，可删除字典
   */
  onDelete(row: SystemFileDTO) {
    this.systemFileService.deleteFileById(row.id).subscribe(
      () => {
        this.msg.success('删除成功');
        this.loadData();
      },
      () => this.msg.error('删除失败'),
      () => this.loadData(),
    );
  }

  ngOnInit() {
    this.loadData();
  }
}
